package com.tjnu.baiyi.dao;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.tjnu.baiyi.entity.TbAlbum;
import com.tjnu.baiyi.entity.TbAlbumVisitor;
import com.tjnu.baiyi.entity.TbUser;

@Repository("tbUserDao")
@Transactional
public class TbUserDAO {
	@Autowired
	@Qualifier("sessionFactory")
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	protected void initDao() {
		// do nothing
	}

	public void save(TbUser transientInstance) {
		try {
			// 保存注册信息
			getCurrentSession().save(transientInstance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void delete(TbUser persistentInstance) {
		try {
			getCurrentSession().delete(persistentInstance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public TbUser findById(java.lang.Integer id) {
		try {
			TbUser instance = (TbUser) getCurrentSession()
					.get(TbUser.class, id);
			return instance;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List<TbUser> findAll() {
		try {
			String queryString = new StringBuffer().append(
					"FROM TbUser ORDER BY userHot DESC").toString();
			Query queryObject = getCurrentSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	// 用户登录
	public TbUser login(String Email, String password) {
		try {
			System.out.println("TbUserDAO.login()");
			String qstr = new StringBuffer().append(
					"FROM TbUser WHERE email = ?").toString();
			Query queryObject = getCurrentSession().createQuery(qstr);
			System.out.println("begin to get list()");
			List<TbUser> list = new ArrayList<TbUser>();
			list = queryObject.setString(0, Email).list();
			System.out.println("first queryObject");
			// 判断邮箱是否存在
			if (list.get(0) != null) {
				System.out.println("email exist");
				// 邮箱存在：判断密码是否正确
				StringBuffer queryString = new StringBuffer();
				queryString.append(" FROM TbUser");
				queryString.append(" WHERE email = ?");
				queryString.append(" AND password = ?");
				queryObject = getCurrentSession().createQuery(
						queryString.toString());
				queryObject.setString(0, Email);
				queryObject.setString(1, password);
				list = queryObject.list();
				if (list.size() == 1) {
					// 密码正确：进入登录成功的页面
					System.out
							.println("list.size != 0 , so return list.get(0)");
					return list.get(0);
				} else {
					// 密码错误：直接返回null
					System.out.println("list.size == 0 , so return null");
					return null;
				}
			} else {
				// 邮箱不存在：直接返回null
				System.out.println("email not exist");
				return null;
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("TbUserDAO : login fail!");
			e.printStackTrace();
			return null;
		}
	}

	// 对某人空间点赞
	public Boolean updateUserHot(Integer id, Integer userHot) {
		try {
			String queryString = new StringBuffer().append(
					"UPDATE TbUser SET userHot =? WHERE userId=?").toString();
			Query queryObject = getCurrentSession().createQuery(queryString)
					.setInteger(0, userHot + 1).setInteger(1, id);
			queryObject.executeUpdate();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	// 获取用户表中所有的邮箱信息
	public List<String> getAllEmailInTbUserTable() {
		try {
			String queryString = new StringBuffer().append(
					"SELECT email FROM TbUser").toString();
			Query queryObject = getCurrentSession().createQuery(queryString);
			List<String> list = queryObject.list();
			for (int i = 0; i < list.size(); i++) {
				System.out.println("email :" + list.get(i));
			}
			return list;
		} catch (Exception e) {
			return null;
		}
	}

	// 添加访问空间的访客记录
	public void updateVisitor(Integer currentUserId, Integer QzoneUserId,
			Integer visitorSize) {
		try {
			// 判断是否有相应的记录
			String validateString = new StringBuffer()
					.append("FROM TbVisitor WHERE tbUserByVisitorId.userId=? AND tbUserByUserId.userId=?")
					.toString();
			Query queryValidateObject = getCurrentSession()
					.createQuery(validateString).setInteger(0, currentUserId)
					.setInteger(1, QzoneUserId);
			List<TbAlbum> validateList = queryValidateObject.list();
			if (validateList.size() != 0) {// 有相应的记录，对记录中的时间字段进行更新
				String queryString1 = new StringBuffer()
						.append("UPDATE tb_visitor SET visit_time = ? WHERE Visitor_id=? AND User_id=?")
						.toString();
				Query queryObject1 = getCurrentSession()
						.createSQLQuery(queryString1)
						.addEntity(TbAlbumVisitor.class)
						.setTimestamp(0, getCurrentTime())
						.setInteger(1, currentUserId)
						.setInteger(2, QzoneUserId);
				int i = queryObject1.executeUpdate();
			} else {// 没有相应的记录，向访问表中添加纪录
				String queryString2 = new StringBuffer()
						.append("INSERT INTO tb_visitor (Visitor_id,visit_time,User_id) VALUES(?,?,?)")
						.toString();
				Query queryObject2 = getCurrentSession()
						.createSQLQuery(queryString2)
						.addEntity(TbAlbumVisitor.class)
						.setInteger(0, currentUserId)
						.setTimestamp(1, getCurrentTime())
						.setInteger(2, QzoneUserId);
				int i = queryObject2.executeUpdate();
				System.out.println("queryObject1.executeUpdate():" + i);
			}
			// 更新该用户的被访问总数
			String queryString2 = new StringBuffer().append(
					"UPDATE tb_user SET visitor_size =? WHERE User_id=?")
					.toString();
			Query queryObject2 = getCurrentSession()
					.createSQLQuery(queryString2).addEntity(TbUser.class)
					.setInteger(0, visitorSize + 1).setInteger(1, QzoneUserId);
			int j = queryObject2.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean isFirstUserHotAndCurrentUser(Integer firstId, Integer userId) {
		String queryString = new StringBuffer().append(
				"select * from tb_friend where Friend_id=? and User_id=?")
				.toString();
		Query queryObject = getCurrentSession().createSQLQuery(queryString)
				.setInteger(0, firstId).setInteger(1, userId);
		List list = queryObject.list();
		if (list.size() != 0) {
			return true;//已经关注
		} else {
			return false;//未关注
		}
	}

	// 获取当前时间
	public Timestamp getCurrentTime() {
		// 使用默认时区和语言环境获得一个日历
		Calendar calender = Calendar.getInstance();
		// 将Calendar类型转换成Date类型
		Date tasktime = (Date) calender.getTime();
		// 设置日期输出的格式
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Timestamp time = Timestamp.valueOf(df.format(tasktime));
		return time;
	}
}